package com.lagou.rpc.consumer.task;

import com.lagou.rpc.api.IUserService;
import com.lagou.rpc.consumer.pojo.ServiceInfo;
import com.lagou.rpc.consumer.zookeeper.ZkHelper;
import com.lagou.rpc.pojo.User;
import org.apache.curator.framework.CuratorFramework;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;

/**
 * @author boting.guo
 * @date 2021/11/14 12:50
 */

public class SimpleTask implements Runnable {
	private CuratorFramework client;

	private ZkHelper zkHelper;

	public SimpleTask(CuratorFramework client, ZkHelper zkHelper) {
		this.client = client;
		this.zkHelper = zkHelper;
	}

	@Override
	public void run() {
		while (true) {

			if (zkHelper.getClientMap().isEmpty()) {
				continue;
			}

			try {
				Thread.sleep(3000);
				ArrayList<Map.Entry<String, ServiceInfo>> entries = new ArrayList<>(zkHelper.getClientMap().entrySet());
				Collections.sort(entries, new Comparator<Map.Entry<String, ServiceInfo>>() {
					@Override
					public int compare(Map.Entry<String, ServiceInfo> o1, Map.Entry<String, ServiceInfo> o2) {
						return (int) (o1.getValue().getUsedTime() - o2.getValue().getUsedTime());
					}
				});


				ServiceInfo serviceInfo = entries.get(0).getValue();
				String domain = entries.get(0).getKey();
				IUserService userService = serviceInfo.getiUserService();

				System.out.println("选择与" + domain + "进行通信");

				long time = System.currentTimeMillis();
				User user = userService.getById(1);
				System.out.println("响应结果为" + user.toString());
				long endTime = System.currentTimeMillis();
				long usedTime = endTime - time;

				System.out.println("与" + domain + "通信耗时为" + usedTime + "ms");

				serviceInfo.setLastTime(endTime);
				serviceInfo.setUsedTime(usedTime);

				client.setData().forPath("/server-registry/" + entries.get(0).getKey(), (endTime + ":" + usedTime).getBytes(StandardCharsets.UTF_8));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
